﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraGrid.Views.Base;
using System.Collections;
using System.Data.SqlClient;

namespace QLKS
{
    public partial class frmQLLoaiKhachHang : DevExpress.XtraEditors.XtraForm
    {
        private DataTable _table = new DataTable();
        private bool _them;
        public delegate void PassData(int num, int total);
        public frmQLLoaiKhachHang()
        {
            InitializeComponent();
            _table.BeginInit();
            _table.Columns.Add("MaLoaiKhach", typeof(int));
            _table.Columns.Add("TenLoaiKhach", typeof(string));             
            _table.EndInit();
            //DevExpress.Skins.SkinManager.EnableFormSkins();
            //DevExpress.UserSkins.BonusSkins.Register();            
        }
        /// <summary>
        /// Enable hoặc disable các control
        /// </summary>
        /// <param name="edit">Disable input</param>
        /// <param name="clear">Xóa trống các input</param>
        public void SetControl(bool edit, bool clear)
        {
            gridControl1.Enabled = !edit;
            #region TextBoxs
            txtName.Properties.ReadOnly = !edit;
            #endregion
            btnInsert.Enabled = !edit;
            btnSave.Enabled = edit;
            btnAbort.Enabled = edit;
            if (gridView1.FocusedRowHandle > -1 && gridControl1.Enabled)
            {
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;                             
            }
            else
            {
                btnUpdate.Enabled = false;
                btnDelete.Enabled = false;                
            }
            #region ClearTexboxs

            if (clear)
            {                
                txtName.Text = string.Empty;                             
            }

            #endregion
        }
        /// <summary>
        /// Nếu _them = true là end-user chọn insert;
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsert_Click(object sender, EventArgs e)
        {
            SetControl(true, true);
            txtName.Focus();
            _them = true;
        }
        private void frmQLKhachHang_Load(object sender, EventArgs e)
        {            
            _table=BUS.LoaiKhachHangBUS.SelectAll().Tables[0];
            gridControl1.DataSource = _table;            
            SetControl(false, false);
        }
        private void GetDataRow()
        {
            DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);
            if (row != null)
            {
                txtName.Text = row[1].ToString();                
            }
        }
        /// <summary>
        /// Lấy Row end-user Focus để gán vào các textbox
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            SetControl(false, false);
            GetDataRow();
        }

        /// <summary>
        /// Nếu _them=false nghĩa là end-user nhấn sửa
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            _them = false;
            SetControl(true, false);
        }
        
        /// <summary>
        /// Hủy thao tác thêm hoặc sửa và bỏ validate
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbort_Click(object sender, EventArgs e)
        {
            var al = new ArrayList((ICollection)dxValidationProvider1.GetInvalidControls());
            foreach (Control c in al)
            {
                dxValidationProvider1.RemoveControlError(c);
            }
            SetControl(false, false);
            GetDataRow();
        }

        /// <summary>
        /// Validate dữ liệu nhập và xem là insert hay update (và thực hiện)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!dxValidationProvider1.Validate())
                return;
            
            DTO.LoaiKhachHangDTO loaikhach = new DTO.LoaiKhachHangDTO()
            {
                TenLoaiKhach = txtName.Text                
            };
            try
            {
                if (_them)
                {
                    int id = BUS.LoaiKhachHangBUS.Insert(loaikhach);
                    _table.Rows.Add(new object[]
                                       {
                                           id, txtName.Text
                                       });                   
                }
                else
                {
                    loaikhach.MaLoaiKhach = Convert.ToInt32(gridView1.GetDataRow(gridView1.FocusedRowHandle)[0]);
                    BUS.LoaiKhachHangBUS.Update(loaikhach);
                    DataRow row = gridView1.GetDataRow(gridView1.FocusedRowHandle);                    
                    row[1] = txtName.Text;                                     
                }
                //gridControl1.DataSource = _table;
            }
            catch (SqlException ex)
            {
                string str = String.Format("Lỗi: {0}", ex.Message);
                MessageBox.Show(str, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            SetControl(false, false);
        }

        /// <summary>
        /// Xóa Selected records
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (gridView1.FocusedRowHandle > -1)
            {
                int[] selectedRows = gridView1.GetSelectedRows();
                int countRows = gridView1.SelectedRowsCount;
                if (
                    MessageBox.Show(String.Format("Bạn muốn xóa {0} loại khách??", countRows), "Thông Báo!",
                                    MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    for (int i = 0; i < countRows; i++)
                    {
                        BUS.LoaiKhachHangBUS.Delete((Int32)gridView1.GetDataRow(selectedRows[i])[0]);
                    }
                    gridView1.DeleteSelectedRows();
                }
            }
            else
            {
                MessageBox.Show("Không có loại khách nào để xóa!", "Thông Báo!");
            }
        }

        /// <summary>
        /// Thoát và xóa dữ liệu chương trình để giải phóng bộ nhớ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            _table.Clear();
            GC.Collect();
            Close();
        }
    }
}